package gof_001_创建型_Create.gof_001_单例_Singleton.gof_011_Serializable;

import java.io.*;

public class SerializableMain {
    private static final String FILE_PATH_STUDENT = "D:/student.txt";
    private static final String FILE_PATH_USER = "D:/user.txt";

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //测试学生类
        testStudent();

        //测试用户类
        testUser();
    }

    private static void testUser() throws IOException, ClassNotFoundException {
        User u1 = User.getInstance();
        System.out.println("u1 = " + u1);

        //在D盘创建 user.txt 文件，并将实例写入到该文件
        File file = new File(FILE_PATH_USER);
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(u1);
        oos.close();
        fos.close();


        //从D盘 user.txt 中读取实例
        FileInputStream fis = new FileInputStream(FILE_PATH_USER);
        ObjectInputStream ois = new ObjectInputStream(fis);
        User u2 = (User) ois.readObject();
        ois.close();
        fis.close();
        System.out.println("u2 = " + u2);
    }

    private static void testStudent() throws IOException, ClassNotFoundException {
        Student s1 = Student.getInstance();
        System.out.println("s1 = " + s1);

        //在D盘创建 student.txt 文件，并将实例写入到该文件
        File file = new File(FILE_PATH_STUDENT);
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(s1);
        oos.close();
        fos.close();


        //从D盘 student.txt 中读取实例
        FileInputStream fis = new FileInputStream(FILE_PATH_STUDENT);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Student s2 = (Student) ois.readObject();
        ois.close();
        fis.close();
        System.out.println("s2 = " + s2);
    }
}
